﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CodeCampServerLite.Core.Domain;
using CodeCampServerLite.Core.Domain.Model;
using CodeCampServerLite.UI.Helpers;
using CodeCampServerLite.UI.Models;

namespace CodeCampServerLite.UI.Controllers
{
	public class ConferenceController : DefaultController
	{
		private readonly IConferenceRepository _repository;
		private readonly IObjectMapper _mapper;

		public ConferenceController(IConferenceRepository repository, IObjectMapper mapper)
		{
			_repository = repository;
			_mapper = mapper;
		}

		public ViewResult Index()
		{
			var list = from conf in _repository.Query()
					   select conf;

			var conferences = list.ToArray();

			var viewModel = _mapper.Map<Conference[], ConferenceListModel[]>(conferences);

			return View(viewModel);
		}

		public ActionResult Show(string confname)
		{
			var conf = _repository.GetByName(confname);

			var viewModel = _mapper.Map<Conference, ConferenceShowModel>(conf);

			return View(viewModel);
		}

		public ActionResult Edit(string confname)
		{
			var conf = _repository.GetByName(confname);

			var viewModel = _mapper.Map<Conference, ConferenceEditModel>(conf);

			return View(viewModel);
		}

		[HttpPost]
		public ActionResult Edit(ConferenceEditModel form)
		{
			var conf = _repository.GetById(form.Id);

			conf.ChangeName(form.Name);

			foreach (var attendeeEditModel in form.Attendees)
			{
				var attendee = conf.GetAttendee(attendeeEditModel.Id);

				attendee.ChangeName(attendeeEditModel.FirstName, attendeeEditModel.LastName);
				attendee.Email = attendeeEditModel.Email;
			}

			return RedirectToRoute("Default", new { controller = "Conference", action = "Index" });
		}

		public ActionResult Register(string confname)
		{
			var conf = _repository.GetByName(confname);

			return View(new AttendeeEditModel
			{
				EventId = conf.Id,
				EventName = conf.Name
			});
		}

		[HttpPost]
		public ActionResult Register(AttendeeEditModel model)
		{
			if (ModelState.IsValid)
			{
				var entity = _repository.GetById(model.EventId);
				var attendee = new Attendee(model.FirstName, model.LastName)
				{
					Email = model.Email
				};
				attendee.RegisterFor(entity);
				return RedirectToAction("AttendeeConfirmation", model);
			}

			return View(model);
		}

		public ActionResult AttendeeConfirmation(AttendeeEditModel model)
		{
			return View(model);
		}
	}
}
